package com.example.combwx.mvp.view;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.combwx.R;
import com.example.combwx.db.UserUtility;
import com.example.combwx.mvp.base.model.BaseEntity;
import com.example.combwx.mvp.base.view.BaseActivity;
import com.example.combwx.mvp.contract.RegisterContract;
import com.example.combwx.mvp.di.DaggerRegisterComponent;
import com.example.combwx.mvp.di.RegisterModels;
import com.example.combwx.mvp.model.HttpCode;
import com.example.combwx.mvp.model.entity.RegisterEntity;
import com.example.combwx.mvp.model.entity.UserEntity;
import com.example.combwx.mvp.presenter.RegisterPresenter;
import com.example.combwx.network.Api;
import com.example.combwx.network.HttpFactory;
import com.example.combwx.network.HttpType;
import com.example.combwx.utils.LogUtils;
import com.example.combwx.utils.ToasetUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ChangeinformationActivity extends
        BaseActivity<RegisterPresenter> implements
        RegisterContract.IRegisterView, View.OnClickListener {

    private static final String TAG = "ChangeinformationActivi";
    private String path;
    private FrameLayout detailLinear;
    private ImageView informationBack;
    private RelativeLayout rlImg;
    private ImageView detailHeadImg;
    private RelativeLayout rlName;
    private TextView detailName;
    private RelativeLayout rlSex;
    private TextView detailSex;
    private RelativeLayout detailBackParent;
    private View detailBackgroundBack;
    private TextView detailCamera;
    private TextView detailOpenPhoto;
    private TextView detailCancel;
    private RelativeLayout detailBackParent2;
    private TextView detailPrivary;
    private TextView detailMan;
    private TextView detailWomen;
    private TextView detailCancel2;
    private View inflate;
    private TextView editNick;
    private int sex_user;
    //    private Uri data1;
    private InformationBroadcast informationBroadcast;
    private int REQUESTPERMISSIONCODE = 100;
    private int REQUESTPHOTOCODE = 101;
    private int REQUESTCAMERACODE = 102;
    public static int CAMERACODE = 0;
    public static int PHOTOCODE = 1;
    private Uri uri;//开启相机时，传递到相机设置相机保存图片路径
    private File file;//开启相机时，保存图片路径
    private int type = -1;//popupwindow开启是传递过来参数，调用开启相机/图库



    @Override
    public View addStatusView() {
        return f(R.id.detail_linear);
    }

    @Override
    public int addcolor() {
        return Color.WHITE;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_changeinformation;
    }

    @Override
    public void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.CALL_PHONE
            }, 101);
        }

        inflate = LayoutInflater.from(getApplicationContext()).inflate(R.layout.view_detail_pop, null);
        editNick = inflate.findViewById(R.id.edit_nickname);
        informationBack = findViewById(R.id.information_back);
        informationBack.setOnClickListener(this::onClick);
        rlImg = findViewById(R.id.rl_img);
        rlImg.setOnClickListener(this::onClick);
        detailHeadImg = findViewById(R.id.detail_head_img);
        rlName = findViewById(R.id.rl_name);
        rlName.setOnClickListener(this::onClick);
        detailName = findViewById(R.id.detail_name);
        rlSex = findViewById(R.id.rl_sex);
        rlSex.setOnClickListener(this::onClick);
        detailSex = findViewById(R.id.detail_sex);
        detailBackParent = findViewById(R.id.detail_back_parent);
        detailBackgroundBack = findViewById(R.id.detail_background_back);
        detailCamera = findViewById(R.id.detail_camera);
        detailOpenPhoto = findViewById(R.id.detail_open_photo);
        detailCancel = findViewById(R.id.detail_cancel);
        detailCamera.setOnClickListener(this::onClick);
        detailOpenPhoto.setOnClickListener(this::onClick);
        detailCancel.setOnClickListener(this::onClick);
        detailBackParent2 = findViewById(R.id.detail_back_parent2);
        detailPrivary = findViewById(R.id.detail_privary);
        detailMan = findViewById(R.id.detail_man);
        detailWomen = findViewById(R.id.detail_women);
        detailCancel2 = findViewById(R.id.detail_cancel2);
        detailPrivary.setOnClickListener(this::onClick);
        detailMan.setOnClickListener(this::onClick);
        detailWomen.setOnClickListener(this::onClick);
        detailCancel2.setOnClickListener(this::onClick);
        informationBroadcast = new InformationBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("xxx");
        registerReceiver(informationBroadcast, intentFilter);
        try {
            List<UserEntity> userEntities = UserUtility.getInstance().getDaoSession().loadAll(UserEntity.class);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Glide.with(ChangeinformationActivity.this).load(userEntities.get(0).user_img).into(detailHeadImg);
                    String user_name = userEntities.get(0).user_name;
                    detailName.setText(user_name);
                    detailSex.setText(userEntities.get(0).user_sex);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public void initData() {

    }

    @Override
    public void inject() {
        DaggerRegisterComponent.builder()
                .registerModels(new RegisterModels(this))
                .build().chang(this);
    }

    @Override
    public void regirefres(BaseEntity entity) {
        LogUtils.show("regirefres" + entity.status);
        if (entity.status.equals("200")) {
            EventBus.getDefault()
                    .postSticky("1");
        }
    }

    //申请权限方法
    private void requestPermission(){
        if (Build.VERSION.SDK_INT<Build.VERSION_CODES.M)
            return;
        if (ContextCompat.checkSelfPermission(
                this, Manifest.permission.READ_EXTERNAL_STORAGE)!=
                PackageManager.PERMISSION_GRANTED&&
                ContextCompat.checkSelfPermission(
                        this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
                        PackageManager.PERMISSION_GRANTED&&
                ContextCompat.checkSelfPermission(
                        this, Manifest.permission.CAMERA)!=
                        PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},
                    REQUESTPERMISSIONCODE);
        }
    }

    //获取申请结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean flag = true;
        if (ContextCompat.checkSelfPermission(
                this, Manifest.permission.READ_EXTERNAL_STORAGE)!=
                PackageManager.PERMISSION_GRANTED)
            flag = false;
        if (ContextCompat.checkSelfPermission(
                this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
                PackageManager.PERMISSION_GRANTED)
            flag = false;
        if (ContextCompat.checkSelfPermission(
                this, Manifest.permission.CAMERA)!=
                PackageManager.PERMISSION_GRANTED)
            flag = false;
        if (!flag){
            ToasetUtils.showMsg("请手动赋予当前应用程序权限");
            finish();
        }
        if (type == 0){
            //开启图库
            openPhoto();
        }else if (type==1){
            //开启相机
            openCamera();
        }
    }

    @Override
    public void onClick(View view) {
        Log.i(TAG, "onClick: 1111");
        switch (view.getId()) {
            case R.id.rl_img:
                Log.i(TAG, "onClick: 222");
                detailBackParent.setVisibility(View.VISIBLE);
                Animation animation_img = AnimationUtils.loadAnimation(this, R.anim.tran);
                detailBackParent.setAnimation(animation_img);
                break;
            case R.id.rl_name:
                Intent intent = new Intent(ChangeinformationActivity.this, ChangeNameAvtivity.class);
                startActivity(intent);
                break;
            case R.id.rl_sex:
                detailBackParent2.setVisibility(View.VISIBLE);
                Animation animation_sex = AnimationUtils.loadAnimation(this, R.anim.tran);
                detailBackParent2.startAnimation(animation_sex);
                break;

            case R.id.detail_camera:
//                path = "/sdcard/DCIM/Camera/" + createName();
//                Intent intent1 = new Intent();
//                intent1.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//                Uri uri = FileProvider.getUriForFile(ChangeinformationActivity.this, "com.example.combwx", new File(path));
//                intent1.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//                startActivityForResult(intent1, 102);
//                detailBackParent2.setVisibility(View.INVISIBLE);
                openCamera();
                break;
            case R.id.detail_open_photo:
//                Intent intent2 = new Intent();
//                intent2.setAction(Intent.ACTION_PICK);
//                intent2.setType("image/*");
//                startActivityForResult(intent2, 111);
//
//                detailBackParent2.setVisibility(View.INVISIBLE);
                openPhoto();
                break;
            case R.id.detail_cancel:
                detailBackParent.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_privary:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailSex.setText("保密");
                    }
                });
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_man:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailSex.setText("男");
                    }
                });
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_women:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailSex.setText("女");
                    }
                });
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_cancel2:
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.information_back:

                String name = detailName.getText().toString().trim();
                String sex = detailSex.getText().toString().trim();
                if (detailSex.getText().toString().equals("男")) {
                    sex_user = 0;
                } else if (detailSex.getText().toString().equals("女")) {
                    sex_user = 1;
                } else {
                    sex_user = 2;
                }

                if (path!=null){
                    upload(path);
                    Log.i("xrn", "onClick: "+path);
                }

                p.getRegis(name, path, sex_user, HttpCode.UPDATEUSERCODE);

                try {
                    List<UserEntity> userEntities = UserUtility.getInstance().getDaoSession().loadAll(UserEntity.class);
                    com.blankj.utilcode.util.LogUtils.json("information_back" + userEntities);
                    for (UserEntity userEntity : userEntities) {
                        userEntity.setUser_name(name);
                        if (path!=null){
                            userEntity.setUser_img(path);
                        }
                        userEntity.setUser_sex(sex);
                        userEntities.add(userEntity);
                        com.blankj.utilcode.util.LogUtils.json(userEntity);
                        UserUtility.getInstance().getDaoSession().update(userEntity);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                EventBus.getDefault()
                        .postSticky("1");
                finish();
                break;
        }
    }

    public String createName() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String format1 = format.format(date);
        return "IMG_" + format1 + ".jpg";
    }

    class InformationBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().contains("xxx")) {
                Log.i(TAG, "onReceive: "+intent.getStringExtra("a"));
                detailName.setText("" + intent.getStringExtra("a"));
            }
        }
    }

    //    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 111 && resultCode == Activity.RESULT_OK) {
//            Uri data1 = data.getData();
//            if (data1==null){
//                return;
//            }else {
////                LogUtils.show("data1:"+data1);
//                Glide.with(ChangeinformationActivity.this)
//                        .load(data1)
//                        .transform(new CenterCrop(), new CenterCrop())
//                        .into(detailHeadImg);
//                upload(data1.toString());
//                detailBackParent.setVisibility(View.INVISIBLE);
//            }
//
//
//        } else if (requestCode == 102 && resultCode == Activity.RESULT_OK) {
//
//            Glide.with(ChangeinformationActivity.this)
//                    .load(path)
//                    .into(detailHeadImg);
//            upload(path);
//            detailBackParent.setVisibility(View.INVISIBLE);
//        }
//    }

    private void openCamera(){
        String name = ""+System.currentTimeMillis();
        file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath(),name+".jpg");
        //判断SDK版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            //SDK版本大于10->兼容处理沙箱机制
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DISPLAY_NAME,name);
            values.put(MediaStore.Images.Media.RELATIVE_PATH,"Pictures");
            values.put(MediaStore.Images.Media.MIME_TYPE,"image/JPEG");
            uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            //7-9
            uri = FileProvider.getUriForFile(this,"com.example.combwx",file);
        }else {
            //低版本
            uri = Uri.fromFile(file);
        }
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        startActivityForResult(intent,102);

    }

    private void openPhoto(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent,101);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            detailBackParent.setVisibility(View.INVISIBLE);
            return;
        }

        //根据requestCode区分图库或相机
        if (101 == requestCode) {

            Cursor cursor = getContentResolver().query(data.getData(), new String[]{MediaStore.Images.Media.DATA},
                    null, null, null);
            path = null;
            while (cursor.moveToNext()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
            Glide.with(this).load(path)
                    .transform(new CenterCrop(), new CircleCrop())
                    .into(detailHeadImg);
            detailBackParent.setVisibility(View.INVISIBLE);
            String[] split = path.split("/");
            Log.i("wxy", "split: "+split[6]);
        }

        if (102 == requestCode) {
            path = null;
            path = file.getAbsolutePath();
            Glide.with(this).load(path)
                    .transform(new CenterCrop(), new CircleCrop())
                    .into(detailHeadImg);
            detailBackParent.setVisibility(View.INVISIBLE);
            String[] split = path.split("/");
            Log.i("wxy", "split: "+split[9]);
        }

    }

    public void upload(String path) {
        //上传用户图片
        File file = new File(path);

        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Builder builder = new MultipartBody.Builder();

        builder.addFormDataPart("file", path, body);

        List<MultipartBody.Part> parts = builder.build().parts();

        HttpFactory.getInstance().factory(HttpType.UPLOADTYPE)
                .getRetrofit()
                .create(Api.class)
                .requestUploadHead(parts)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseEntity baseEntity) {
                        Toast.makeText(ChangeinformationActivity.this, "上传成功" + baseEntity.message, Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(informationBroadcast);
    }
}
